package edu.ptit.jad.model;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;

import org.jsoup.Jsoup;

/**
 * 
 * @author PhuongDo
 * 
 */
public class Ad extends Content {

	private int id;
	private String title;
	private String description;
	private String url;
	private String cates;

	public Ad() {

	}

	public Ad(String row) {

		this.convertToObject(row);
	}

	private void convertToObject(String row) {
		try {

			// System.err.println(row);
			String[] splits = row.split("::::");

			id = Integer.parseInt(splits[0].trim());
			title = splits[1].trim();
			description = splits[2].trim();
			//url = splits[3].trim();
			cates = splits[3].trim();

		} catch (Exception exception) {

			// exception.printStackTrace();
			System.err.println("Convert to object error! at " + row);

			// throw new AdException("Convert to object error! at " + row);

		}

	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getUrlContent() {

		URL oracle;
		StringBuilder builder = new StringBuilder();
		try {
			oracle = new URL(this.url.trim());

			BufferedReader in = new BufferedReader(new InputStreamReader(
					oracle.openStream()));

			String inputLine;

			while ((inputLine = in.readLine()) != null)
				builder.append(inputLine);

			in.close();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return Jsoup.parse(builder.toString()).text()
				.replaceAll("(\r\n|\r|\n|\n\r|\t|\t\r\n)", "");

	}

	@Override
	public String toString() {

		return String.format("%d::::%s::::%s::::%s", id, title, description,
				this.getUrlContent());

	}

	public String getCates() {
		return cates;
	}

	public void setCates(String cates) {
		this.cates = cates;
	}

}
